#include"myheadd.h"

static void ensure_history_dir()//确保历史目录存在
{
    struct stat st;
    if(stat("./history",&st) == -1)
    {
        mkdir("./history",0777);
    }
}

static void get_private_filename(char *filename, const char *user1, const char *user2) //私聊
{
    ensure_history_dir();
   
    if (strcmp(user1, user2) < 0)  //比ack码 按字典序排序用户名，保证文件名唯一（避免a_b和b_a两个文件）
    {
        snprintf(filename, 100, "./history/%s_%s.txt", user1, user2);
    } 
    else 
    {
        snprintf(filename, 100, "./history/%s_%s.txt", user2, user1);
    }
}
//群聊
static void get_group_filename(char *filename, const char *ip, int port) 
{
    ensure_history_dir();
    snprintf(filename, 100, "./history/%s_%d.txt", ip, port);
}

// 获取当前时间戳
static void get_current_time(char *time_str) 
{
    time_t now;
    struct tm *t;
    time(&now);
    t = localtime(&now);
    strftime(time_str, 20, "%Y-%m-%d %H:%M:%S", t);  // 格式化时间
}

int write_history(ChatType type, const char *sender, const char *target, const char *content) 
{
    if (!sender || !target || !content) 
    {
        fprintf(stderr, "无效的消息参数\n");
        return -1;
    }

    char filename[100] = {0};
    ChatRecord record;
    record.type = type;
    strncpy(record.sender, sender, sizeof(record.sender)-1);
    strncpy(record.content, content, sizeof(record.content)-1);
    get_current_time(record.time);

    
    if (type == PRIVATE_CHAT) // 区分私聊和群聊，生成对应文件名
    {
        strncpy(record.receiver, target, sizeof(record.receiver)-1);
        get_private_filename(filename, sender, target);
    } 
    else 
    {
        strncpy(record.receiver, target, sizeof(record.receiver)-1);// 存储群标识（IP:端口）
        char ip[20];
        int port;
        sscanf(target, "%[^:]:%d", ip, &port);  // 从"IP:端口"解析
        get_group_filename(filename, ip, port);
    }

   
    FILE *fp = fopen(filename, "a+"); // 追加写入记录（二进制方式便于读取解析）
    if (!fp) 
    {
        perror("打开历史记录文件失败");
        return -1;
    }
    fwrite(&record, sizeof(ChatRecord), 1, fp);
    fclose(fp);
    return 0;
}

int read_history(ChatType type, const char *user, const char *target) 
{
    if (!user || !target) 
    {
        fprintf(stderr, "无效的查询参数\n");
        return -1;
    }

    char filename[100] = {0};
    if (type == PRIVATE_CHAT) 
    {
        get_private_filename(filename, user, target);
        printf("===== 与 %s 的聊天记录 =====\n", target);
    } 
    else 
    {
        char ip[20];
        int port;
        sscanf(target, "%[^:]:%d", ip, &port);
        get_group_filename(filename, ip, port);
        printf("===== 群聊 %s 的聊天记录 =====\n", target);
    }

    FILE *fp = fopen(filename, "r+");
    if (!fp) 
    {
        printf("暂无聊天记录\n");
        return -1;
    }

    ChatRecord record;
    while (fread(&record, sizeof(ChatRecord), 1, fp) == 1) 
    {
        printf("[%s] %s: %s\n", record.time, record.sender, record.content);
    }
    fclose(fp);
    printf("===========================\n");
    return 0;
}